<template>
  <div class="revenueAnalysis">
    <div class="contentTopTitle">
      <div class="fl">
        <div class="title">码号-月-核心平台主量收入</div>
      </div>
    </div>
    <div>
      <el-form :inline="true" :model="form" label-width="70px" class="formList">
        <span v-if="this.activeName == 'first' || this.activeName == 'third'">
          <el-form-item label="账期：" style="width: 27%">
            <el-date-picker
              v-model="form.startAcctMonth"
              style="width: 120px"
              value-format="yyyyMM"
              type="month"
              placeholder="选择月"
            ></el-date-picker>
            <span>~</span>
            <el-date-picker
              v-model="form.endAcctMonth"
              style="width: 120px"
              value-format="yyyyMM"
              type="month"
              placeholder="选择月"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="区域" style="width: 15%">
            <dx-cascader
              :area_id.sync="form.areaId"
              style="width: 120px"
              :area_name.sync="form.areaName"
              :area_lvl.sync="form.areaLvl"
              ref="cascader"
            />
          </el-form-item>
        </span>
        <span v-if="this.activeName == 'second' || this.activeName == 'fouth'">
          <el-form-item label="账期：">
            <el-date-picker
              v-model="form.acctMonth"
              value-format="yyyyMM"
              type="month"
              placeholder="选择月"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="区域">
            <dx-cascader
              :area_id.sync="form.areaId"
              :area_name.sync="form.areaName"
              :area_lvl.sync="form.areaLvl"
              ref="cascader"
            />
          </el-form-item>
        </span>
        <el-form-item label="客户群" style="width: 12%">
          <el-select v-model="form.level" clearable>
            <el-option
              v-for="(it, i) in level"
              :key="i"
              :label="it.indexName"
              :value="it.indexCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类别" style="width: 12%">
          <el-select v-model="form.type" clearable>
            <el-option
              v-for="(it, i) in types"
              :key="i"
              :label="it.label"
              :value="it.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="融合/单产品" style="width: 17%" label-width="80px">
          <el-select v-model="form.productCode" clearable style="width: 120px">
            <el-option
              v-for="(it, i) in productCode"
              :key="i"
              :label="it.indexName"
              :value="it.indexCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="checkedBox" style="width: 12%">
          <el-checkbox
            v-model="form.checked"
            @change="handleCheckedCitiesChange"
            >环比</el-checkbox
          >
        </el-form-item>
      </el-form>
      <div style="display: flex; margin: 10px 0; justify-content: end">
        <el-button size="small" type="primary" @click="search">查询</el-button>
        <el-button
          size="small"
          type="orange"
          @click="batchxport"
          v-if="this.activeName == 'first' || this.activeName == 'third'"
          >三级导出</el-button
        >
        <el-button
          size="small"
          type="orange"
          @click="btnBoxs"
          v-if="this.activeName == 'first' || this.activeName == 'third'"
          >二级导出</el-button
        >
        <el-button size="small" type="orange" @click="exportModal"
          >导出</el-button
        >
      </div>
    </div>
    <!-- <div class="table-content clearfix"> -->
    <div class="content">
      <el-tabs v-model="activeName" @tab-click="handleClick" ref="tabs">
        <el-tab-pane label="分账期" name="first">
          <tab1 :rowData="tableData" :colDefList="colDefList" ref="tab1"></tab1>
        </el-tab-pane>
        <el-tab-pane label="分区域" name="second">
          <tab2 :rowData="tableData" :colDefList="colDefList" ref="tab2"></tab2>
        </el-tab-pane>
        <el-tab-pane label="分账期" name="third">
          <tab3 :rowData="tableData" :colDefList="colDefList" ref="tab3"></tab3>
        </el-tab-pane>
        <el-tab-pane label="分区域" name="fouth">
          <tab4 :rowData="tableData" :colDefList="colDefList" ref="tab4"></tab4>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import tab1 from "@/views/budget/revenueAnalysis/revenueAnalysis_tab1";
import tab2 from "@/views/budget/revenueAnalysis/revenueAnalysis_tab2";
import tab3 from "@/views/budget/revenueAnalysis/revenueAnalysis_tab3";
import tab4 from "@/views/budget/revenueAnalysis/revenueAnalysis_tab4";
import prefixAPI from "@/api/prefixAPI";
import { getSessionStorage } from "@/common/js/storage";
import { $budgetAPI } from "@/api";
import axios from "axios";
import { getCookie } from "@/common/js/cookie";

export default {
  name: "revenueAnalysis",
  components: {
    tab1,
    tab2,
    tab3,
    tab4,
  },
  data() {
    return {
      backRecord: false,
      form: {
        areaId: "",
        startAcctMonth: "",
        endAcctMonth: "",
        checked: false,
        acctMonth: "",
        level: "",
        type: "",
        productCode: "",
      },
      activeName: "first",
      tabVal: 1,
      flag: false,
      accountInfo: "",
      tableData: [],
      colDefList: [],
      indexValue: "",
      level: [],
      productCode: [],
      types: [
        { label: "全部", value: "" },
        { label: "存存量", value: "CCL" },
        { label: "存增量", value: "CZL" },
        { label: "增量", value: "ZL" },
      ],
    };
  },
  computed: {
    areaSelect() {
      return this.form.areaSelect;
    },
  },
  created() {
    // this.accountInfo = JSON.parse(getSessionStorage("accountInfo"));
    // this.form.areaId = this.accountInfo.areaId;
    let query = this.$route.query;
    this.backRecord = typeof query.backRecord === undefined ? true : false;
    // console.log( typeof(query.backRecord) == 'undefined')//true
    if (this.backRecord) {
      this.form.areaId = query.areaId;
      this.form.acctMonth = query.acctMonth;
      this.form.endAcctMonth = query.endAcctMonth;
      this.form.startAcctMonth = query.startAcctMonth;
    } else {
      this.accountInfo = JSON.parse(getSessionStorage("accountInfo"));
      this.form.areaId = this.accountInfo.areaId;
      // this.form.acctMonth = this.moment().subtract(1,'months').format('YYYYMM')
      // this.form.endAcctMonth = this.moment().subtract(1,'months').format('YYYYMM');
      // this.form.startAcctMonth = this.moment().subtract(1,'months').subtract(1,'year').format('YYYYMM')
    }
    this.getNewAcctMonth();
    this.getChoiceList();
  },

  watch: {
    // 'form.checked' : {  // 监听ruleForm的isbrand(是否品牌)被选中了
    //   handler (newVal, oldVal) {
    //     this.showTabPane(this.form.checked, 'first') // tab-brand是id名字，自己去html中查看tabs选项卡的dom节点id名
    //     this.showTabPane(this.form.checked, 'third')
    //     this.showTabPane(this.form.checked, 'second')
    //     this.showTabPane(this.form.checked, 'fouth')
    //   },
    //   immediate: true
    // },
  },
  mounted() {
    // this.init();
    var that = this;
    $budgetAPI.getProductList({}, (res) => {
      that.productCode = res.content;
    });
    this.hideTabs();
  },
  methods: {
    handleCheckedCitiesChange() {
      this.init();
      this.hideTabs();
      this.flag = !this.flag;
    },
    getChoiceList() {
      var that = this;

      $budgetAPI.getChoiceListNew({}, (res) => {
        that.level = res.content.cLevel;
      });
    },
    //tab的显示隐藏
    hideTabs() {
      this.$nextTick(function () {
        if (this.form.checked == false) {
          this.$refs.tabs.$children[0].$refs.tabs[2].style.display = "none";
          this.$refs.tabs.$children[0].$refs.tabs[3].style.display = "none";
          this.$refs.tabs.$children[0].$refs.tabs[0].style.display =
            "inline-block";
          this.$refs.tabs.$children[0].$refs.tabs[1].style.display =
            "inline-block";
        } else {
          this.$refs.tabs.$children[0].$refs.tabs[0].style.display = "none";
          this.$refs.tabs.$children[0].$refs.tabs[1].style.display = "none";
          this.$refs.tabs.$children[0].$refs.tabs[2].style.display =
            "inline-block";
          this.$refs.tabs.$children[0].$refs.tabs[3].style.display =
            "inline-block";
        }
      });
    },
    // showTabPane (control, pane) {
    //         let dom = '';
    //         this.$nextTick(() => {
    //           dom = document.getElementById(pane)
    //           console.log(dom)
    //           if (control == "false") {
    //            if(pane == 'first' || pane == 'second'){
    //                dom.style.display = 'inline-block';
    //            }else{
    //               dom.style.display = 'none';
    //            }
    //           } else {
    //            if(pane == 'third' || pane == 'fouth'){
    //                dom.style.display = 'inline-block';
    //            }else{
    //               dom.style.display = 'none';
    //            }
    //           }
    //         })
    //       },
    //查询
    search() {
      let params = {
        acctMonth: this.form.acctMonth,
        endAcctMonth: this.form.endAcctMonth,
        startAcctMonth: this.form.startAcctMonth,
        areaId: this.form.areaId ? this.form.areaId : this.accountInfo.areaId,
        tabVal: this.tabVal,
        flag: this.form.checked,
        cLevel: this.form.level,
        custTypeNew: this.form.type,
        productCode: this.form.productCode,
      };

      this.listResourceData(params);
    },
    //导出
    exportModal() {
      let areaId = this.form.areaId;
      let acctMonth = this.form.acctMonth;
      let startAcctMonth = this.form.startAcctMonth;
      let endAcctMonth = this.form.endAcctMonth;
      let flag = this.flag;
      let token = getCookie("token");

      let cLevel = this.form.level;
      let custTypeNew = this.form.type;
      let productCode = this.form.productCode;

      if (this.activeName == "first" || this.activeName == "third") {
        // 根据不同模式切换不同的路径
        if (process.env.NODE_ENV == "development") {
          window.location.href =
            prefixAPI.loc +
            `/api/corePlatform/exportCorePlatformIncomeByAreaId?areaId=${areaId}&startAcctMonth=${startAcctMonth}&endAcctMonth=${endAcctMonth}&flag=${flag}&cLevel=${cLevel}&custTypeNew=${custTypeNew}&productCode=${productCode}&token=${token}`;
        } else if (process.env.NODE_ENV == "production") {
          window.location.href =
            prefixAPI.hp +
            `/api/corePlatform/exportCorePlatformIncomeByAreaId?areaId=${areaId}&startAcctMonth=${startAcctMonth}&endAcctMonth=${endAcctMonth}&flag=${flag}&cLevel=${cLevel}&custTypeNew=${custTypeNew}&productCode=${productCode}&token=${token}`;
        }
      }
      if (this.activeName == "second" || this.activeName == "fouth") {
        // 根据不同模式切换不同的路径
        if (process.env.NODE_ENV == "development") {
          window.location.href =
            prefixAPI.loc +
            `/api/corePlatform/exportCorePlatformIncomeByAcctMonth?areaId=${areaId}&acctMonth=${acctMonth}&flag=${flag}&cLevel=${cLevel}&custTypeNew=${custTypeNew}&productCode=${productCode}&token=${token}`;
        } else if (process.env.NODE_ENV == "production") {
          window.location.href =
            prefixAPI.hp +
            `/api/corePlatform/exportCorePlatformIncomeByAcctMonth?areaId=${areaId}&acctMonth=${acctMonth}&flag=${flag}&cLevel=${cLevel}&custTypeNew=${custTypeNew}&productCode=${productCode}&token=${token}`;
        }
      }
    },
    // 二级导出
    btnBoxs() {
      // axios({
      //   method: "get",
      //   url: "/api/corePlatform/exportCorePlatformIncomeTwoLevel",
      //   responseType: "blob",
      //   params: {
      //     areaId: this.form.areaId,
      //     startAcctMonth: this.form.startAcctMonth,
      //     endAcctMonth: this.form.endAcctMonth,
      //     token: getCookie("token"),
      //     flag: this.flag,
      //   },
      //   headers: {
      //     "content-type": "application/json",
      //   },
      // })
      //   .then(function (response) {
      //     console.log(response, "====");
      //     if (response.data.type == "application/vnd.ms-excel") {
      //       const filename = response.headers["content-disposition"];
      //       const blob = new Blob([response.data]);
      //       var downloadElement = document.createElement("a");
      //       var href = window.URL.createObjectURL(blob);
      //       downloadElement.href = href;
      //       downloadElement.download = filename.split("filename=")[1];
      //       document.body.appendChild(downloadElement);
      //       downloadElement.click();
      //       document.body.removeChild(downloadElement);
      //       window.URL.revokeObjectURL(href);
      //     }
      //   })
      // .catch(function (error) {
      //   console.log(error, "===");
      // });
      let areaId = this.form.areaId;
      let startAcctMonth = this.form.startAcctMonth;
      let endAcctMonth = this.form.endAcctMonth;
      let token = getCookie("token");
      let flag = this.flag;
      if (process.env.NODE_ENV == "development") {
        window.location.href =
          prefixAPI.loc +
          `/api/corePlatform/exportCorePlatformIncomeTwoLevel?areaId=${areaId}&flag=${flag}&startAcctMonth=${startAcctMonth}&endAcctMonth=${endAcctMonth}&token=${token}`;
      } else if (process.env.NODE_ENV == "production") {
        window.location.href =
          prefixAPI.hp +
          `/api/corePlatform/exportCorePlatformIncomeTwoLevel?areaId=${areaId}&flag=${flag}&startAcctMonth=${startAcctMonth}&endAcctMonth=${endAcctMonth}&token=${token}`;
      }
    },
    // 三级导出
    batchxport() {
      let areaId = this.form.areaId;
      let startAcctMonth = this.form.startAcctMonth;
      let endAcctMonth = this.form.endAcctMonth;
      let token = getCookie("token");
      let flag = this.flag;
      if (process.env.NODE_ENV == "development") {
        window.location.href =
          prefixAPI.loc +
          `/api/corePlatform/batchExportCorePlatformIncomeByAreaId?areaId=${areaId}&flag=${flag}&startAcctMonth=${startAcctMonth}&endAcctMonth=${endAcctMonth}&token=${token}`;
      } else if (process.env.NODE_ENV == "production") {
        window.location.href =
          prefixAPI.hp +
          `/api/corePlatform/batchExportCorePlatformIncomeByAreaId?areaId=${areaId}&flag=${flag}&startAcctMonth=${startAcctMonth}&endAcctMonth=${endAcctMonth}&token=${token}`;
      }
      // 根据不同模式切换不同的路径
    },
    listResourceData(params) {
      if (this.form.checked == false) {
        switch (params.tabVal) {
          case 1:
            this.$refs.tab1.tableLoading = true;
            break;
          case 2:
            this.$refs.tab2.tableLoading = true;
            break;
        }
      } else {
        switch (params.tabVal) {
          case 3:
            this.$refs.tab3.tableLoading = true;
            break;
          case 4:
            this.$refs.tab4.tableLoading = true;
            break;
        }
      }
      if (this.form.checked == true) {
        if (params.tabVal == 3 || params.tabVal == 1) {
          this.activeName = "third";
          $budgetAPI.getCorePlatformIncomeListByAreaId(
            params,
            (res) => {
              if (res.code == 0) {
                this.tableData = [];
                this.colDefList = [];
                this.tableData = res.content.data;
                this.colDefList = res.content.dateAreaList;
                res.content.data.map((item, index) => {
                  item.dataList.map((ele, ind) => {
                    item["indexValue" + ind] = ele.indexValue;
                    item["indexHbValue" + ind] = ele.indexHbValue;
                  });
                });
                setTimeout(() => {
                  this.$refs.tab3.init();
                  this.$refs.tab3.tableLoading = false;
                }, 500);
              } else {
                this.alertError(res);
              }
            },
            (err) => {}
          );
        } else if (params.tabVal == 4 || params.tabVal == 2) {
          var that = this;
          $budgetAPI.getCorePlatformIncomeListByAcctMonth(
            params,
            (res) => {
              if (res.code == 0) {
                this.tableLoading = false;
                this.tableData = [];
                // that.colDefList = [];
                this.colDefList = res.content.areaNames;
                // this.contentList = res.content.data[1].dataList;
                this.tableData = res.content.data;
                res.content.data.map((item, index) => {
                  item.dataList.map((ele, ind) => {
                    item["indexValue" + ind] = ele.indexValue;
                    item["indexHbValue" + ind] = ele.indexHbValue;
                  });
                });
                // this.$refs.tab4.init();
                // this.$refs.tab4.tableLoading = false;
                setTimeout(() => {
                  this.$refs.tab4.init();
                  this.$refs.tab4.tableLoading = false;
                }, 500);
              } else {
                this.alertError(res);
              }
            },
            (err) => {}
          );
        }
      } else if (this.form.checked == false) {
        if (params.tabVal == 3 || params.tabVal == 1) {
          var that = this;
          $budgetAPI.getCorePlatformIncomeListByAreaId(
            params,
            (res) => {
              if (res.code == 0) {
                this.tableLoading = false;
                this.tableData = [];
                // that.colDefList = [];
                //  this.colDefList = ['合计', ...res.content.dateAreaList];
                this.colDefList = [...res.content.dateAreaList];
                // this.contentList = res.content.data[1].dataList;
                this.tableData = res.content.data;
                res.content.data.map((item, index) => {
                  item.dataList.map((ele, ind) => {
                    item["indexValue" + ind] = ele.indexValue;
                  });
                });
                setTimeout(() => {
                  this.$refs.tab1.init();
                  this.$refs.tab1.tableLoading = false;
                }, 500);
              } else {
                this.alertError(res);
              }
            },
            (err) => {}
          );
        }
        if (params.tabVal == 4 || params.tabVal == 2) {
          var that = this;
          $budgetAPI.getCorePlatformIncomeListByAcctMonth(
            params,
            (res) => {
              if (res.code == 0) {
                this.tableLoading = false;
                this.tableData = [];
                // that.colDefList = [];
                this.colDefList = res.content.areaNames;
                // this.contentList = res.content.data[1].dataList;
                this.tableData = res.content.data;
                res.content.data.map((item, index) => {
                  item.dataList.map((ele, ind) => {
                    item["indexValue" + ind] = ele.indexValue;
                  });
                });
                setTimeout(() => {
                  this.$refs.tab2.init();
                  this.$refs.tab2.tableLoading = false;
                }, 500);
              } else {
                this.alertError(res);
              }
            },
            (err) => {}
          );
        }
      }
    },
    init() {
      if (this.$route.query.backRecord) {
        let query = this.$route.query;
        let params = {
          acctMonth: query.acctMonth,
          areaId: query.areaId,
          endAcctMonth: query.endAcctMonth,
          startAcctMonth: query.startAcctMonth,
          tabVal: 1,
          flag: query.flag,
          cLevel: this.form.level,
          custTypeNew: this.form.type,
        };
        this.listResourceData(params);
      } else {
        if (this.form.checked == false) {
          if (this.activeName == "first" || this.activeName == "third") {
            this.activeName = "first";
            let params = {
              acctMonth: this.form.acctMonth,
              endAcctMonth: this.form.endAcctMonth,
              startAcctMonth: this.form.startAcctMonth,
              areaId: this.form.areaId
                ? this.form.areaId
                : this.accountInfo.areaId,
              tabVal: 1,
              flag: false,
              productCode: this.form.productCode,
            };
            this.listResourceData(params);
          } else if (
            this.activeName == "second" ||
            this.activeName == "fouth"
          ) {
            this.activeName = "second";
            let params = {
              acctMonth: this.form.acctMonth,
              endAcctMonth: this.form.endAcctMonth,
              startAcctMonth: this.form.startAcctMonth,
              areaId: this.form.areaId
                ? this.form.areaId
                : this.accountInfo.areaId,
              tabVal: 2,
              flag: false,
              productCode: this.form.productCode,
            };
            this.listResourceData(params);
          }
        } else {
          if (this.activeName == "first" || this.activeName == "third") {
            this.activeName == "third";
            let params = {
              acctMonth: this.form.acctMonth,
              endAcctMonth: this.form.endAcctMonth,
              startAcctMonth: this.form.startAcctMonth,
              areaId: this.form.areaId
                ? this.form.areaId
                : this.accountInfo.areaId,
              tabVal: 3,
              flag: true,
              productCode: this.form.productCode,
            };
            this.listResourceData(params);
          } else if (
            this.activeName == "second" ||
            this.activeName == "fouth"
          ) {
            this.activeName = "fouth";
            let params = {
              acctMonth: this.form.acctMonth,
              endAcctMonth: this.form.endAcctMonth,
              startAcctMonth: this.form.startAcctMonth,
              areaId: this.form.areaId
                ? this.form.areaId
                : this.accountInfo.areaId,
              tabVal: 4,
              flag: true,
              productCode: this.form.productCode,
            };

            this.listResourceData(params);
          }
        }
      }
    },
    //数据点击切换页请求不同的数据
    handleClick(tab, event) {
      let params = {
        acctMonth: this.form.acctMonth,
        endAcctMonth: this.form.endAcctMonth,
        startAcctMonth: this.form.startAcctMonth,
        areaId: this.form.areaId ? this.form.areaId : this.accountInfo.areaId,
        tabVal: null,
        flag: this.flag,
        productCode: this.form.productCode,
      };
      if (tab.name == "first") {
        params.tabVal = 1;
        this.tabVal = 1;
        params.flag = false;
        this.flag = false;
        this.listResourceData(params);
      }
      if (tab.name == "second") {
        params.tabVal = 2;
        this.tabVal = 2;
        params.flag = false;
        this.flag = false;
        this.listResourceData(params);
      }
      if (tab.name == "third") {
        params.tabVal = 3;
        this.tabVal = 3;
        params.flag = true;
        this.flag = true;
        this.listResourceData(params);
      }
      if (tab.name == "fouth") {
        params.tabVal = 4;
        this.tabVal = 4;
        params.flag = true;
        this.flag = true;
        this.listResourceData(params);
      }
    },
    //获取账期
    getNewAcctMonth() {
      let areaId = this.form.areaId;
      let that = this;
      $budgetAPI.getNewAcctMonth(
        { areaId: areaId },
        (res) => {
          if (res || res.code == 0) {
            that.form.endAcctMonth = res.content.maxAcctMonth;
            that.form.startAcctMonth = res.content.preSixMonth;
            that.form.acctMonth = res.content.maxAcctMonth;
            this.init();
          }
        },
        (err) => {}
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.revenueAnalysis {
  .table-content {
    .table-header {
      display: flex;
      justify-content: space-between;
      .btn-right {
        display: flex;
      }

      .table-title {
        font-size: 14px;
        font-weight: bold;
        height: 30px;
        line-height: 30px;

        span {
          display: inline-block;
          width: 5px;
          height: 5px;
          background-color: #418ee9;
          border-radius: 1000%;
          overflow: hidden;
          margin-right: 10px;
          margin-bottom: 3px;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.revenueAnalysis {
  .formList {
    .el-form-item {
      width: 22%;
      .el-form-item__content {
        width: calc(100% - 80px);
      }
    }
    .el-form-item.width50 {
      width: 40%;
      .el-form-item__content .el-input {
        width: 45%;
      }
    }
    .el-form-item.width30 {
      width: 23%;
      .el-form-item__content {
        width: 100%;
      }
    }
    .el-form-item.checkedBox {
      margin-left: 20px;
      width: 10%;
      .el-checkbox__inner {
        border-radius: 100%;
      }
    }
    .el-form-item.btnBox {
      margin-bottom: 0px;
      width: 18%;
      margin-right: 0;

      .el-form-item__content {
        display: flex;
      }
    }
  }
}
</style>
